#!/usr/bin/env python

# Copyright (c) 2007 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import os
import pygame
import config

from tape import Tape
from controls import Controls

class GraphicalTuringMachine:

    (
    FG,
    BG
    ) = range(2)

    def __init__(self, surface, image_file):
        self.image = pygame.image.load(os.path.join(config.data_dir,\
                'turingmachine.png')).convert_alpha()
        self.surface = surface
        self.color = [(198, 93, 0), (0, 0, 0)]

        self.font = pygame.font.Font(config.font_path, 26)
        self.states_rendered = {}

        pos_x = (surface.get_width() - self.image.get_width()) / 2
        self.pos = (pos_x, 5)

        self.turingmachine = None

        self.tape = Tape(surface, 50)
        tape_pos = (pos_x + (self.get_width() / 2) - 23, self.pos[1] + 153)
        self.tape.set_base_position(tape_pos)

        self.controls = Controls(surface)

    def get_position(self):
        return self.pos

    def get_width(self):
        return self.image.get_width()

    def set_turingmachine(self, turingmachine):
        self.turingmachine = turingmachine
        self.turingmachine.reset()
        self.tape.set_tape_alphabet(self.turingmachine.get_input_alphabet() + \
                self.turingmachine.get_tape_alphabet())

        for state in turingmachine.get_states():
            self.states_rendered[state] = self.font.render(\
                    state, True, 
                    self.color[GraphicalTuringMachine.FG])

    def play_pause(self):
        self.controls.play_pause()

    def reset(self):
        self.turingmachine.reset()
        self.controls.reset()

    def draw(self):
        self.tape.draw(self.turingmachine.get_tape(),\
                       self.turingmachine.get_head())
        self.surface.blit(self.image, self.pos)

        st = self.states_rendered[self.turingmachine.get_current_state()]
        pos = (self.pos[0] + (self.image.get_width() - st.get_width()) / 2,
               self.pos[1] + 38)
        self.surface.blit(st, pos)

        self.controls.draw()

